package com.nuaa.qianru.run;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.eclipse.paho.client.mqttv3.*;

import java.util.LinkedList;

public class PushCallback1 implements MqttCallback,MqttCallbackExtended {
	private int count=0;
	private int i=0;
	private int j=0;
	private LinkedList<Double> linkedList=new LinkedList<>();
	private LinkedList<Double> turan=new LinkedList<>();
	private MqttServer1 mqttServer=MqttServer1.getInstance();

	double pre;

	public void connectionLost(Throwable cause) {
        // 连接丢失后，一般在这里面进行重连  
        System.out.println("连接断开，可以做重连");   
   
    }  
    
    public void deliveryComplete(IMqttDeliveryToken token) {
        System.out.println("deliveryComplete---------" + token.isComplete());  

    }

    public void messageArrived(String topic, MqttMessage message) throws Exception {
        // subscribe后得到的消息会执行到这里面
			/*
			 * System.out.println("接收消息主题 : " + topic); System.out.println("接收消息Qos : " +
			 * message.getQos()); System.out.println("接收消息内容 : " + new
			 * String(message.getPayload(),"UTF-8"));
			 */
			String mess=new String(message.getPayload(),"UTF-8");

			if(!"close".equals(mess)){
				JSONObject jsonObject = JSON.parseObject(mess);

				JSONArray jsonArray=jsonObject.getJSONArray("data");

				Double temps[][]= jsonArray.getJSONObject(0).getObject("data",Double[][].class);

				Double  me=temps[0][0]/10;
				i++;
				linkedList.add(me );
				if(i==12){
					Double d[]=new Double[12];
					linkedList.toArray(d);
					double res[]=Waring.linearFit(d);
					double k=res[1];
					double b=res[0];
					if(k>0.1){
						count++;
						if(count>=3){
							mqttServer.publishMessage("warn1","温度渐变型故障,3",1);
//							new Client9().start();
						}
					}else{
						count=0;
					}
					linkedList.clear();
					i=0;
				}
				j++;
				turan.add(me);

				if(j==4){
					Double s[]=new Double[4];
					turan.toArray(s);
					double ans[]=Waring.linearFit(s);
					double k1=ans[1];
					double b=ans[0];
					mqttServer.publishMessage("prev1",me+","+pre,1);
					pre=preTemp(k1,b);
					double aa=0;
					if(k1>0){
						aa=k1*k1;
					}else{
						aa=-k1*k1;
					}
					mqttServer.publishMessage("tubian1",String.valueOf(aa),1);
					if(aa>15){
						mqttServer.publishMessage("warn1","温度突变型故障,2",1);
//						new Client9().start();
					}
					turan.poll();
					j--;
				}

			}
	 } 
	@Override
	public void connectComplete(boolean reconnect, String serverURI) {
		 try {
			Client1.getClient().subscribe("Sample/1C36A51AB21089E/temperature", 1);
		} catch (MqttException e) {
		
			e.printStackTrace();
		} 
	}
	public double preTemp(double k,double b){
		return 5*k+b;
	}
}
